const app = require('../app');
const Record = require('../mongodb/record');
const ObjectID = require('mongodb').ObjectID;
// const md5 = require('md5-node');

const CallController = {

    postBack: async (ctx, next) => {

        let query = ctx.request.query;
        let clickId = query.click_id;

        if (!clickId) {
            await ctx.json({
                code: "500",
                msg: 'param error: click_id is null'
            });
            return;
        }

        // 创建 postback对象，并为其字段赋值
        let record = null;

        // 先查询，如果存在则驳回
        try{
            await Record.findOne({'_id': ObjectID(clickId)}, (err, doc) => {
                record = doc;
            });
        }catch (e) {
            await ctx.json({
                code: "500",
                msg: 'param error: click_id is invalid'
            });
            return;
        }

        if (!record) {
            await ctx.json({
                code: 500,
                msg: 'click_id not exists, please check your click_id'
            });
            return;
        }

        if (record.is_sub) {
            await ctx.json({
                code: 500,
                msg: 'click_id already exists'
            });
            return;
        }

        await Record.updateOne({'_id': ObjectID(clickId)}, {
            'is_sub': 1
        }).then((doc) => {
            // 成功处理
            ctx.json({
                code: "200",
                msg: 'success'
            });
        }).catch(err => {
            // 错误处理
            ctx.json({
                code: "500",
                msg: 'server error: postback error'
            });
            app.logger.error(err);
        });

    }

};

module.exports = CallController;
